#include "qexpandopenglwidget.h"

// Instantiate static variables
std::map<std::string, QExpandOpenGLWidget::Texture2D>    QExpandOpenGLWidget::ResourceManager::Textures;
std::map<std::string, QExpandOpenGLWidget::Shader>       QExpandOpenGLWidget::ResourceManager::Shaders;

unsigned int QExpandOpenGLWidget::TextureFromFile(const char *path, const std::string &directory, QExpandOpenGLWidget* parent)    {
    std::string filename = std::string(path);
    filename = directory + '/' + filename;

    unsigned int textureID;
    parent->glGenTextures(1, &textureID);

    int width, height, nrComponents;
    unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0);
    if (data)
    {
        GLenum format;
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;

        parent->glBindTexture(GL_TEXTURE_2D, textureID);
        parent->glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        parent->glGenerateMipmap(GL_TEXTURE_2D);

        parent->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        parent->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        parent->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        parent->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        stbi_image_free(data);
    }
    else
    {
        std::cout << "Texture failed to load at path: " << path << std::endl;
        stbi_image_free(data);
    }

    return textureID;
}

void QExpandOpenGLWidget::resizeGL(int w, int h) {
    glViewport(0, 0, w, h);
}

unsigned int QExpandOpenGLWidget::loadTexture(char const *path)
{
    unsigned int textureID;
    glGenTextures(1, &textureID);

    int width, height, nrComponents;
    unsigned char *data = stbi_load(path, &width, &height, &nrComponents, 0);
    if (data)
    {
        GLenum format;
        if (nrComponents == 1)
            format = GL_RED;
        else if (nrComponents == 3)
            format = GL_RGB;
        else if (nrComponents == 4)
            format = GL_RGBA;

        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
        glGenerateMipmap(GL_TEXTURE_2D);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        stbi_image_free(data);
    }
    else
    {
        std::cout << "Texture failed to load at path: " << path << std::endl;
        stbi_image_free(data);
    }

    return textureID;
}

// 加载立方体纹理
unsigned int QExpandOpenGLWidget::loadCubemap(std::vector<std::string> faces) {
    unsigned int textureID;
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);

    int width, height, nrComponents;
    for (unsigned int i = 0; i < faces.size(); i++)
    {
        unsigned char *data = stbi_load(faces[i].c_str(), &width, &height, &nrComponents, 0);
        if (data)
        {
            glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
            stbi_image_free(data);
        }
        else
        {
            std::cout << "Cubemap texture failed to load at path: " << faces[i] << std::endl;
            stbi_image_free(data);
        }
    }
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

    return textureID;
}

void QExpandOpenGLWidget::Shader::readShaderFile(const char* vertexPath, const char* fragmentPath, const char* geometryPath) {
    QFile vs(vertexPath), fs(fragmentPath), geometry(geometryPath);
    QString vertexStr, fragmentStr, geometryStr;
    if (vs.open(QIODevice::ReadOnly))
    {
        QByteArray array = vs.readAll();//读取文本中全部文件
        vertexStr = QString(array);
    }
    vs.close();
    if (fs.open(QIODevice::ReadOnly))
    {
        QByteArray array = fs.readAll();//读取文本中全部文件
        fragmentStr = QString(array);
    }
    fs.close();
    if(geometry.fileName()!=nullptr){
        if (geometry.open(QIODevice::ReadOnly))
        {
            QByteArray array = geometry.readAll();//读取文本中全部文件
            geometryStr = QString(array);
        }
        geometry.close();
    }
    char* pGeometryStr = nullptr;
    if(!geometryStr.isEmpty()){
        pGeometryStr = (char*)geometryStr.toStdString().c_str();
    }
    readShaderStr(vertexStr.toStdString().c_str(), fragmentStr.toStdString().c_str(), pGeometryStr);

}

void QExpandOpenGLWidget::Shader::readShaderStr(const char* vertexStr, const char* fragmentStr, const char* geometryStr){
    GLuint vertexShader = m_parent->glCreateShader(GL_VERTEX_SHADER);
    m_parent->glShaderSource(vertexShader, 1, &vertexStr, NULL);
    m_parent->glCompileShader(vertexShader);

    int success;
    char infoLog[512];
    m_parent->glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        m_parent->glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        qDebug() << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog;
    }

    GLuint fragmentShader = m_parent->glCreateShader(GL_FRAGMENT_SHADER);

    m_parent->glShaderSource(fragmentShader, 1, &fragmentStr, NULL);
    m_parent->glCompileShader(fragmentShader);

    m_parent->glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        m_parent->glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
        qDebug() << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog;
    }
    GLuint geometryShader;
    if(geometryStr!=nullptr){
        geometryShader = m_parent->glCreateShader(GL_GEOMETRY_SHADER);

        m_parent->glShaderSource(geometryShader, 1, &geometryStr, NULL);
        m_parent->glCompileShader(geometryShader);

        m_parent->glGetShaderiv(geometryShader, GL_COMPILE_STATUS, &success);
        if (!success)
        {
            m_parent->glGetShaderInfoLog(geometryShader, 512, NULL, infoLog);
            qDebug() << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog;
        }
    }
    shaderProgram = m_parent->glCreateProgram();
    m_parent->glAttachShader(shaderProgram, vertexShader);
    m_parent->glAttachShader(shaderProgram, fragmentShader);
    if(geometryStr!=nullptr){
        m_parent->glAttachShader(shaderProgram, geometryShader);
    }

    m_parent->glLinkProgram(shaderProgram);

    m_parent->glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
    if (!success) {
        m_parent->glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
        qDebug() << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog;
    }
    m_parent->glDeleteShader(vertexShader);
    m_parent->glDeleteShader(fragmentShader);
    if(geometryStr != nullptr){
        m_parent->glDeleteShader(geometryShader);
    }

}

void QExpandOpenGLWidget::Shader::checkCompileErrors(GLuint shader, std::string type) {
    GLint success;
    GLchar infoLog[1024];
    if(type != "PROGRAM")
    {
        m_parent->glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
        if(!success)

        {
            m_parent->glGetShaderInfoLog(shader, 1024, NULL, infoLog);
            std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
        }
    }
    else
    {
        m_parent->glGetProgramiv(shader, GL_LINK_STATUS, &success);
        if(!success)
        {
            m_parent->glGetProgramInfoLog(shader, 1024, NULL, infoLog);
            std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << std::endl;
        }
    }
}

void QExpandOpenGLWidget::Shader::use()
{
    m_parent->glUseProgram(shaderProgram);
}

QExpandOpenGLWidget::Shader &QExpandOpenGLWidget::Shader::Use()
{
    m_parent->glUseProgram(this->shaderProgram);
    return *this;
}

void QExpandOpenGLWidget::Shader::SetFloat(const GLchar *name, GLfloat value, GLboolean useShader)
{
    if (useShader)
        this->Use();
    m_parent->glUniform1f(m_parent->glGetUniformLocation(this->shaderProgram, name), value);
}
void QExpandOpenGLWidget::Shader::SetInteger(const GLchar *name, GLint value, GLboolean useShader)
{
    if (useShader)
        this->Use();
    m_parent->glUniform1i(m_parent->glGetUniformLocation(this->shaderProgram, name), value);
}
void QExpandOpenGLWidget::Shader::SetVector2f(const GLchar *name, GLfloat x, GLfloat y, GLboolean useShader)
{
    if (useShader)
        this->Use();
    m_parent->glUniform2f(m_parent->glGetUniformLocation(this->shaderProgram, name), x, y);
}
void QExpandOpenGLWidget::Shader::SetVector2f(const GLchar *name, const glm::vec2 &value, GLboolean useShader)
{
    if (useShader)
        this->Use();
    m_parent->glUniform2f(m_parent->glGetUniformLocation(this->shaderProgram, name), value.x, value.y);
}
void QExpandOpenGLWidget::Shader::SetVector3f(const GLchar *name, GLfloat x, GLfloat y, GLfloat z, GLboolean useShader)
{
    if (useShader)
        this->Use();
    m_parent->glUniform3f(m_parent->glGetUniformLocation(this->shaderProgram, name), x, y, z);
}
void QExpandOpenGLWidget::Shader::SetVector3f(const GLchar *name, const glm::vec3 &value, GLboolean useShader)
{
    if (useShader)
        this->Use();
    m_parent->glUniform3f(m_parent->glGetUniformLocation(this->shaderProgram, name), value.x, value.y, value.z);
}
void QExpandOpenGLWidget::Shader::SetVector4f(const GLchar *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w, GLboolean useShader)
{
    if (useShader)
        this->Use();
    m_parent->glUniform4f(m_parent->glGetUniformLocation(this->shaderProgram, name), x, y, z, w);
}
void QExpandOpenGLWidget::Shader::SetVector4f(const GLchar *name, const glm::vec4 &value, GLboolean useShader)
{
    if (useShader)
        this->Use();
    m_parent->glUniform4f(m_parent->glGetUniformLocation(this->shaderProgram, name), value.x, value.y, value.z, value.w);
}
void QExpandOpenGLWidget::Shader::SetMatrix4(const GLchar *name, const glm::mat4 &matrix, GLboolean useShader)
{
    if (useShader)
        this->Use();
    m_parent->glUniformMatrix4fv(m_parent->glGetUniformLocation(this->shaderProgram, name), 1, GL_FALSE, glm::value_ptr(matrix));
}

void QExpandOpenGLWidget::Shader::setBool(const std::string &name, bool value)
{
    m_parent->glUniform1i(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), (int)value);
}

void QExpandOpenGLWidget::Shader::setInt(const std::string &name, int value)
{
    m_parent->glUniform1i(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), value);
}

// ------------------------------------------------------------------------
void QExpandOpenGLWidget::Shader::setFloat(const std::string &name, float value)
{
    m_parent->glUniform1f(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), value);
}

// ------------------------------------------------------------------------
void QExpandOpenGLWidget::Shader::setVec2(const std::string &name, const glm::vec2 &value)
{
    m_parent->glUniform2fv(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), 1, &value[0]);
}

void QExpandOpenGLWidget::Shader::setVec2(const std::string &name, float x, float y)
{
    m_parent->glUniform2f(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), x, y);
}

// ------------------------------------------------------------------------
void QExpandOpenGLWidget::Shader::setVec3(const std::string &name, const glm::vec3 &value)
{
    m_parent->glUniform3fv(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), 1, &value[0]);
}

void QExpandOpenGLWidget::Shader::setVec3(const std::string &name, float x, float y, float z)
{
    m_parent->glUniform3f(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), x, y, z);
}

// ------------------------------------------------------------------------
void QExpandOpenGLWidget::Shader::setVec4(const std::string &name, const glm::vec4 &value)
{
    m_parent->glUniform4fv(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), 1, &value[0]);
}

void QExpandOpenGLWidget::Shader::setVec4(const std::string &name, float x, float y, float z, float w)
{
    m_parent->glUniform4f(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), x, y, z, w);
}

// ------------------------------------------------------------------------
void QExpandOpenGLWidget::Shader::setMat2(const std::string &name, const glm::mat2 &mat)
{
    m_parent->glUniformMatrix2fv(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}

// ------------------------------------------------------------------------
void QExpandOpenGLWidget::Shader::setMat3(const std::string &name, const glm::mat3 &mat)
{
    m_parent->glUniformMatrix3fv(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}

// ------------------------------------------------------------------------
void QExpandOpenGLWidget::Shader::setMat4(const std::string &name, const glm::mat4 &mat)
{
    m_parent->glUniformMatrix4fv(m_parent->glGetUniformLocation(shaderProgram, name.c_str()), 1, GL_FALSE, &mat[0][0]);
}

// constructor
QExpandOpenGLWidget::Mesh::Mesh(std::vector<Vertex> vertices, std::vector<unsigned int> indices, std::vector<Texture> textures, QExpandOpenGLWidget *parent)
{
    this->vertices = vertices;
    this->indices = indices;
    this->textures = textures;
    this->m_parent = parent;
    // now that we have all the required data, set the vertex buffers and its attribute pointers.
    setupMesh();
}

// render the mesh
void QExpandOpenGLWidget::Mesh::Draw(Shader &shader)
{
    // bind appropriate textures
    unsigned int diffuseNr  = 1;
    unsigned int specularNr = 1;
    unsigned int normalNr   = 1;
    unsigned int heightNr   = 1;
    for(unsigned int i = 0; i < textures.size(); i++)
    {
        m_parent->glActiveTexture(GL_TEXTURE0 + i); // active proper texture unit before binding
        // retrieve texture number (the N in diffuse_textureN)
        std::string number;
        std::string name = textures[i].type;
        if(name == "texture_diffuse")
            number = std::to_string(diffuseNr++);
        else if(name == "texture_specular")
            number = std::to_string(specularNr++); // transfer unsigned int to string
        else if(name == "texture_normal")
            number = std::to_string(normalNr++); // transfer unsigned int to string
        else if(name == "texture_height")
            number = std::to_string(heightNr++); // transfer unsigned int to string

        // now set the sampler to the correct texture unit
        m_parent->glUniform1i(m_parent->glGetUniformLocation(shader.shaderProgram, (name + number).c_str()), i);
        // and finally bind the texture
        m_parent->glBindTexture(GL_TEXTURE_2D, textures[i].id);
    }

    // draw mesh
    m_parent->glBindVertexArray(VAO);
    m_parent->glDrawElements(GL_TRIANGLES, static_cast<unsigned int>(indices.size()), GL_UNSIGNED_INT, 0);
    m_parent->glBindVertexArray(0);

    // always good practice to set everything back to defaults once configured.
    m_parent->glActiveTexture(GL_TEXTURE0);
}

// initializes all the buffer objects/arrays
void QExpandOpenGLWidget::Mesh::setupMesh()
{
    // create buffers/arrays
    m_parent->glGenVertexArrays(1, &VAO);
    m_parent->glGenBuffers(1, &VBO);
    m_parent->glGenBuffers(1, &EBO);

    m_parent->glBindVertexArray(VAO);
    // load data into vertex buffers
    m_parent->glBindBuffer(GL_ARRAY_BUFFER, VBO);
    // A great thing about structs is that their memory layout is sequential for all its items.
    // The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which
    // again translates to 3/2 floats which translates to a byte array.
    m_parent->glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);

    m_parent->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    m_parent->glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW);

    // set the vertex attribute pointers
    // vertex Positions
    m_parent->glEnableVertexAttribArray(0);
    m_parent->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
    // vertex normals
    m_parent->glEnableVertexAttribArray(1);
    m_parent->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Normal));
    // vertex texture coords
    m_parent->glEnableVertexAttribArray(2);
    m_parent->glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, TexCoords));
    // vertex tangent
    m_parent->glEnableVertexAttribArray(3);
    m_parent->glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Tangent));
    // vertex bitangent
    m_parent->glEnableVertexAttribArray(4);
    m_parent->glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, Bitangent));
    // ids
    m_parent->glEnableVertexAttribArray(5);
    m_parent->glVertexAttribIPointer(5, 4, GL_INT, sizeof(Vertex), (void*)offsetof(Vertex, m_BoneIDs));

    // weights
    m_parent->glEnableVertexAttribArray(6);
    m_parent->glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, m_Weights));
    m_parent->glBindVertexArray(0);
}

void QExpandOpenGLWidget::Model::Draw(Shader &shader)
{
    for(unsigned int i = 0; i < meshes.size(); i++)
        meshes[i].Draw(shader);
}

// loads a model with supported ASSIMP extensions from file and stores the resulting meshes in the meshes vector.
void QExpandOpenGLWidget::Model::loadModel(std::string const &path)
{
    // read file via ASSIMP
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
    // check for errors
    if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero
    {
        std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl;
        return;
    }
    // retrieve the directory path of the filepath
    directory = path.substr(0, path.find_last_of('/'));

    // process ASSIMP's root node recursively
    processNode(scene->mRootNode, scene);
}

// processes a node in a recursive fashion. Processes each individual mesh located at the node and repeats this process on its children nodes (if any).
void QExpandOpenGLWidget::Model::processNode(aiNode *node, const aiScene *scene)
{
    // process each mesh located at the current node
    for(unsigned int i = 0; i < node->mNumMeshes; i++)
    {
        // the node object only contains indices to index the actual objects in the scene.
        // the scene contains all the data, node is just to keep stuff organized (like relations between nodes).
        aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
        meshes.push_back(processMesh(mesh, scene));
    }
    // after we've processed all of the meshes (if any) we then recursively process each of the children nodes
    for(unsigned int i = 0; i < node->mNumChildren; i++)
    {
        processNode(node->mChildren[i], scene);
    }

}

QExpandOpenGLWidget::Mesh QExpandOpenGLWidget::Model::processMesh(aiMesh *mesh, const aiScene *scene)
{
    // data to fill
    std::vector<Vertex> vertices;
    std::vector<unsigned int> indices;
    std::vector<Texture> textures;

    // walk through each of the mesh's vertices
    for(unsigned int i = 0; i < mesh->mNumVertices; i++)
    {
        Vertex vertex;
        glm::vec3 vector; // we declare a placeholder vector since assimp uses its own vector class that doesn't directly convert to glm's vec3 class so we transfer the data to this placeholder glm::vec3 first.
        // positions
        vector.x = mesh->mVertices[i].x;
        vector.y = mesh->mVertices[i].y;
        vector.z = mesh->mVertices[i].z;
        vertex.Position = vector;
        // normals
        if (mesh->HasNormals())
        {
            vector.x = mesh->mNormals[i].x;
            vector.y = mesh->mNormals[i].y;
            vector.z = mesh->mNormals[i].z;
            vertex.Normal = vector;
        }
        // texture coordinates
        if(mesh->mTextureCoords[0]) // does the mesh contain texture coordinates?
        {
            glm::vec2 vec;
            // a vertex can contain up to 8 different texture coordinates. We thus make the assumption that we won't
            // use models where a vertex can have multiple texture coordinates so we always take the first set (0).
            vec.x = mesh->mTextureCoords[0][i].x;
            vec.y = mesh->mTextureCoords[0][i].y;
            vertex.TexCoords = vec;
            // tangent
            vector.x = mesh->mTangents[i].x;
            vector.y = mesh->mTangents[i].y;
            vector.z = mesh->mTangents[i].z;
            vertex.Tangent = vector;
            // bitangent
            vector.x = mesh->mBitangents[i].x;
            vector.y = mesh->mBitangents[i].y;
            vector.z = mesh->mBitangents[i].z;
            vertex.Bitangent = vector;
        }
        else
            vertex.TexCoords = glm::vec2(0.0f, 0.0f);

        vertices.push_back(vertex);
    }
    // now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices.
    for(unsigned int i = 0; i < mesh->mNumFaces; i++)
    {
        aiFace face = mesh->mFaces[i];
        // retrieve all indices of the face and store them in the indices vector
        for(unsigned int j = 0; j < face.mNumIndices; j++)
            indices.push_back(face.mIndices[j]);
    }
    // process materials
    aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
    // we assume a convention for sampler names in the shaders. Each diffuse texture should be named
    // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER.
    // Same applies to other texture as the following list summarizes:
    // diffuse: texture_diffuseN
    // specular: texture_specularN
    // normal: texture_normalN

    // 1. diffuse maps
    std::vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
    textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
    // 2. specular maps
    std::vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
    textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
    // 3. normal maps
    std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal");
    textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
    // 4. height maps
    std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
    textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());

    // return a mesh object created from the extracted mesh data
    return QExpandOpenGLWidget::Mesh(vertices, indices, textures, m_parent);
}

// checks all material textures of a given type and loads the textures if they're not loaded yet.
// the required info is returned as a Texture struct.
std::vector<QExpandOpenGLWidget::Texture> QExpandOpenGLWidget::Model::loadMaterialTextures(aiMaterial *mat, aiTextureType type, std::string typeName)
{
    std::vector<QExpandOpenGLWidget::Texture> textures;
    for(unsigned int i = 0; i < mat->GetTextureCount(type); i++)
    {
        aiString str;
        mat->GetTexture(type, i, &str);
        // check if texture was loaded before and if so, continue to next iteration: skip loading a new texture
        bool skip = false;
        for(unsigned int j = 0; j < textures_loaded.size(); j++)
        {
            if(std::strcmp(textures_loaded[j].path.data(), str.C_Str()) == 0)
            {
                textures.push_back(textures_loaded[j]);
                skip = true; // a texture with the same filepath has already been loaded, continue to next one. (optimization)
                break;
            }
        }
        if(!skip)
        {   // if texture hasn't been loaded already, load it
            QExpandOpenGLWidget::Texture texture;
            texture.id = QExpandOpenGLWidget::TextureFromFile(str.C_Str(), this->directory, m_parent);
            texture.type = typeName;
            texture.path = str.C_Str();
            textures.push_back(texture);
            textures_loaded.push_back(texture);  // store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures.
        }
    }
    return textures;
}

QExpandOpenGLWidget* QExpandOpenGLWidget::ResourceManager::parent = nullptr;

QExpandOpenGLWidget::Shader QExpandOpenGLWidget::ResourceManager::LoadShader(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile, std::string name)
{
    auto shader = loadShaderFromFile(vShaderFile, fShaderFile, gShaderFile);
    shader.m_parent = parent;
    Shaders[name] = shader;
    return Shaders[name];
}

QExpandOpenGLWidget::Shader QExpandOpenGLWidget::ResourceManager::GetShader(std::string name)
{
    return Shaders[name];
}

QExpandOpenGLWidget::Texture2D QExpandOpenGLWidget::ResourceManager::LoadTexture(const GLchar *file, GLboolean alpha, std::string name)
{
    Textures[name] = loadTextureFromFile(file, alpha);
    return Textures[name];
}

QExpandOpenGLWidget::Texture2D QExpandOpenGLWidget::ResourceManager::GetTexture(std::string name)
{
    return Textures[name];
}

void QExpandOpenGLWidget::ResourceManager::Clear()
{
    // (Properly) delete all shaders
    for (auto iter : Shaders)
        parent->glDeleteProgram(iter.second.shaderProgram);
    // (Properly) delete all textures
    for (auto iter : Textures)
        parent->glDeleteTextures(1, &iter.second.ID);
}

QExpandOpenGLWidget::Shader QExpandOpenGLWidget::ResourceManager::loadShaderFromFile(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile)
{
    // 2. Now create shader object from source code
    QExpandOpenGLWidget::Shader shader(parent);
    shader.readShaderFile(vShaderFile, fShaderFile, gShaderFile);
    return shader;
}

QExpandOpenGLWidget::Texture2D QExpandOpenGLWidget::ResourceManager::loadTextureFromFile(const GLchar *file, GLboolean alpha)
{
    // Create Texture object
    QExpandOpenGLWidget::Texture2D texture(parent);
    if (alpha)
    {
        texture.Internal_Format = GL_RGBA;
        texture.Image_Format = GL_RGBA;
    }
    // Load image
    int width, height;
    unsigned char* image = SOIL_load_image(file, &width, &height, 0, texture.Image_Format == GL_RGBA ? SOIL_LOAD_RGBA : SOIL_LOAD_RGB);
    // Now generate texture
    texture.Generate(width, height, image);
    // And finally free image data
    SOIL_free_image_data(image);
    return texture;
}

QExpandOpenGLWidget::SpriteRenderer::SpriteRenderer(const Shader &shader, QExpandOpenGLWidget *parent)
{
    this->shader = shader;
    this->m_parent = parent;
    this->initRenderData();
}

QExpandOpenGLWidget::SpriteRenderer::~SpriteRenderer()
{
    m_parent->glDeleteVertexArrays(1, &this->VAO);
}

void QExpandOpenGLWidget::SpriteRenderer::initRenderData()
{
    // Configure VAO/VBO
    GLuint VBO;
    GLfloat vertices[] = {
        // Pos      // Tex
        0.0f, 1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 1.0f, 0.0f,
        0.0f, 0.0f, 0.0f, 0.0f,

        0.0f, 1.0f, 0.0f, 1.0f,
        1.0f, 1.0f, 1.0f, 1.0f,
        1.0f, 0.0f, 1.0f, 0.0f
    };

    m_parent-> glGenVertexArrays(1, &this->quadVAO);
    m_parent->glGenBuffers(1, &VBO);

    m_parent->glBindBuffer(GL_ARRAY_BUFFER, VBO);
    m_parent->glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    m_parent->glBindVertexArray(this->quadVAO);
    m_parent->glEnableVertexAttribArray(0);
    m_parent->glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
    m_parent->glBindBuffer(GL_ARRAY_BUFFER, 0);
    m_parent->glBindVertexArray(0);
}

void QExpandOpenGLWidget::SpriteRenderer::DrawSprite(const QExpandOpenGLWidget::Texture2D &texture, glm::vec2 position, glm::vec2 size, GLfloat rotate, glm::vec3 color)
{
    // Prepare transformations
    this->shader.Use();
    glm::mat4 model = glm::mat4(1.0f);;
    model = glm::translate(model, glm::vec3(position, 0.0f));  // First translate (transformations are: scale happens first, then rotation and then finall translation happens; reversed order)

    model = glm::translate(model, glm::vec3(0.5f * size.x, 0.5f * size.y, 0.0f)); // Move origin of rotation to center of quad
    model = glm::rotate(model, rotate, glm::vec3(0.0f, 0.0f, 1.0f)); // Then rotate
    model = glm::translate(model, glm::vec3(-0.5f * size.x, -0.5f * size.y, 0.0f)); // Move origin back

    model = glm::scale(model, glm::vec3(size, 1.0f)); // Last scale

    this->shader.SetMatrix4("model", model);

    // Render textured quad
    this->shader.SetVector3f("spriteColor", color);

    m_parent->glActiveTexture(GL_TEXTURE0);
    texture.Bind();

    m_parent->glBindVertexArray(this->quadVAO);
    m_parent->glDrawArrays(GL_TRIANGLES, 0, 6);
    m_parent->glBindVertexArray(0);
}


QExpandOpenGLWidget::Game::Game(GLuint width, GLuint height, QExpandOpenGLWidget* parent)
    : State(GAME_ACTIVE), Keys(), Width(width), Height(height), m_parent(parent)
{

}

QExpandOpenGLWidget::Game::~Game()
{
    delete Renderer;
    delete Player;
}
// Initial size of the player paddle
const glm::vec2 PLAYER_SIZE(100, 20);
// Initial velocity of the player paddle
const GLfloat PLAYER_VELOCITY(500.0f);
void QExpandOpenGLWidget::Game::Init()
{
    // Load shaders
    ResourceManager::LoadShader(":resource/sprite.vs", ":resource/sprite.fs", nullptr, "sprite");
    // Configure shaders
    glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(this->Width), static_cast<GLfloat>(this->Height), 0.0f, -1.0f, 1.0f);
    ResourceManager::GetShader("sprite").Use().SetInteger("sprite", 0);
    ResourceManager::GetShader("sprite").SetMatrix4("projection", projection);
    // Load textures
    ResourceManager::LoadTexture("D:/Material/background.jpg", GL_FALSE, "background");
    ResourceManager::LoadTexture("D:/Material/awesomeface.png", GL_TRUE, "face");
    ResourceManager::LoadTexture("D:/Material/block.png", GL_FALSE, "block");
    ResourceManager::LoadTexture("D:/Material/block_solid.png", GL_FALSE, "block_solid");
    ResourceManager::LoadTexture("D:/Material/paddle.png", true, "paddle");
    // Set render-specific controls
    Renderer = new SpriteRenderer(ResourceManager::GetShader("sprite"), m_parent);
    // Load levels
    GameLevel one; one.Load("D:/Material/levels/one.lvl", this->Width, this->Height * 0.5);
    GameLevel two; two.Load("D:/Material/levels/two.lvl", this->Width, this->Height * 0.5);
    GameLevel three; three.Load("D:/Material/levels/three.lvl", this->Width, this->Height * 0.5);
    GameLevel four; four.Load("D:/Material/levels/four.lvl", this->Width, this->Height * 0.5);
    this->Levels.push_back(one);
    this->Levels.push_back(two);
    this->Levels.push_back(three);
    this->Levels.push_back(four);
    this->Level = 0;
    // Configure game objects
    glm::vec2 playerPos = glm::vec2(this->Width / 2 - PLAYER_SIZE.x / 2, this->Height - PLAYER_SIZE.y);
    Player = new GameObject(playerPos, PLAYER_SIZE, ResourceManager::GetTexture("paddle"));
}

void QExpandOpenGLWidget::Game::Update(GLfloat dt)
{

}


void QExpandOpenGLWidget::Game::ProcessInput(GLfloat dt)
{

}

void QExpandOpenGLWidget::Game::Render()
{    // Render
    if (this->State == GAME_ACTIVE)
    {
        // Draw background
        Renderer->DrawSprite(ResourceManager::GetTexture("background"), glm::vec2(0, 0), glm::vec2(this->Width, this->Height), 0.0f);
        // Draw level
        this->Levels[this->Level].Draw(*Renderer);
        // Draw player
        Player->Draw(*Renderer);
    }
}

QExpandOpenGLWidget::GameObject::GameObject()
    : Position(0.0f, 0.0f), Size(1.0f, 1.0f), Velocity(0.0f), Color(1.0f), Rotation(0.0f), Sprite(), IsSolid(false), Destroyed(false) { }

QExpandOpenGLWidget::GameObject::GameObject(glm::vec2 pos, glm::vec2 size, Texture2D sprite, glm::vec3 color, glm::vec2 velocity)
    : Position(pos), Size(size), Velocity(velocity), Color(color), Rotation(0.0f), Sprite(sprite), IsSolid(false), Destroyed(false) { }

void QExpandOpenGLWidget::GameObject::Draw(SpriteRenderer &renderer)
{
    renderer.DrawSprite(this->Sprite, this->Position, this->Size, this->Rotation, this->Color);
}

void QExpandOpenGLWidget::GameLevel::Load(const GLchar *file, GLuint levelWidth, GLuint levelHeight)
{
    // 清空过期数据
    this->Bricks.clear();
    // 从文件中加载
    GLuint tileCode;
    GameLevel level;
    std::string line;
    std::ifstream fstream(file);
    std::vector<std::vector<GLuint>> tileData;
    if (fstream)
    {
        while (std::getline(fstream, line)) // 读取关卡文件的每一行
        {
            std::istringstream sstream(line);
            std::vector<GLuint> row;
            while (sstream >> tileCode) // 读取被空格分隔的每个数字
                row.push_back(tileCode);
            tileData.push_back(row);
        }
        if (tileData.size() > 0)
            this->init(tileData, levelWidth, levelHeight);
    }
}

void QExpandOpenGLWidget::GameLevel::init(std::vector<std::vector<GLuint>> tileData, GLuint lvlWidth, GLuint lvlHeight)
{
    // 计算每个维度的大小
    GLuint height = tileData.size();
    GLuint width = tileData[0].size();
    GLfloat unit_width = lvlWidth / static_cast<GLfloat>(width);
    GLfloat unit_height = lvlHeight / height;
    // 基于tileDataC初始化关卡
    for (GLuint y = 0; y < height; ++y)
    {
        for (GLuint x = 0; x < width; ++x)
        {
            // 检查砖块类型
            if (tileData[y][x] == 1)
            {
                glm::vec2 pos(unit_width * x, unit_height * y);
                glm::vec2 size(unit_width, unit_height);
                GameObject obj(pos, size,
                               ResourceManager::GetTexture("block_solid"),
                               glm::vec3(0.8f, 0.8f, 0.7f)
                               );
                obj.IsSolid = GL_TRUE;
                this->Bricks.push_back(obj);
            }
            else if (tileData[y][x] > 1)
            {
                glm::vec3 color = glm::vec3(1.0f); // 默认为白色
                if (tileData[y][x] == 2)
                    color = glm::vec3(0.2f, 0.6f, 1.0f);
                else if (tileData[y][x] == 3)
                    color = glm::vec3(0.0f, 0.7f, 0.0f);
                else if (tileData[y][x] == 4)
                    color = glm::vec3(0.8f, 0.8f, 0.4f);
                else if (tileData[y][x] == 5)
                    color = glm::vec3(1.0f, 0.5f, 0.0f);

                glm::vec2 pos(unit_width * x, unit_height * y);
                glm::vec2 size(unit_width, unit_height);
                this->Bricks.push_back(
                            GameObject(pos, size, ResourceManager::GetTexture("block"), color)
                            );
            }
        }
    }
}
void QExpandOpenGLWidget::GameLevel::Draw(SpriteRenderer &renderer)
{
    for (GameObject &tile : this->Bricks)
        if (!tile.Destroyed)
            tile.Draw(renderer);
}

GLboolean QExpandOpenGLWidget::GameLevel::IsCompleted()
{
    for (GameObject &tile : this->Bricks)
        if (!tile.IsSolid && !tile.Destroyed)
            return GL_FALSE;
    return GL_TRUE;
}
